package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.MultiImageAdapter;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.PhotoBean;
import com.sx.zongzhi.bean.ServiceObjectBean;
import com.sx.zongzhi.bean.ServiceRecordDetailBean;
import com.sx.zongzhi.bean.ServicerBean;
import com.sx.zongzhi.presenter.ServiceRecordDetailPest;
import com.sx.zongzhi.presenter.UploadFilePest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IServiceRecordDetailView;
import com.sx.zongzhi.view.UploadFileView;
import com.sx.zongzhi.widget.AudioDialog;
import com.sx.zongzhi.widget.LoadDialog;
import com.zero.smallvideorecord.MediaRecorderActivity;
import com.zero.smallvideorecord.model.MediaRecorderConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 新增服务记录
 */
public class AddServiceRecordActivity extends BaseActivity implements UploadFileView ,IServiceRecordDetailView{

    @BindView(R.id.tv_Time)
    TextView tv_Time;
    @BindView(R.id.et_ServiceLocal)
    EditText et_ServiceLocal;
    @BindView(R.id.tv_Worker)
    TextView tv_Worker;
    @BindView(R.id.et_OtherWorker)
    EditText et_OtherWorker;
    @BindView(R.id.tv_WorkerObject)
    TextView tv_WorkerObject;
    @BindView(R.id.et_ServiceContent)
    EditText et_ServiceContent;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    private Disposable disposable;
    private String currentActivity="";
    /**上传的文件类型 0：文字 1:图片 2: 音频 3：视频*/
    private int FILE_TYPE;
    private SparseArray<String> type=new SparseArray();
    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    /**提交的文件地址*/
    private List<PhotoBean> upDatafile = new ArrayList<>();
    /**服务人员*/
    private ServicerBean.RowsBean servicerBean;
    /**服务对象*/
    private ServiceObjectBean.RowsBean serviceObjBean;
    /**服务对象大类 服务对象小类*/
    private String objectMoudle,objectType;
    private  AudioDialog audioDialog;


    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_service_record);
        currentActivity=getIntent().getStringExtra(Global.ACTIVITY_FRAGMENT);
        FILE_TYPE=getIntent().getIntExtra("FileType",0);
        setTitleName("服务记录新增");
        setTitleRight("提交");
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        type.put(0,"10");
        type.put(1,"70");
        type.put(2,"30");
        type.put(3,"50");
        if (FILE_TYPE!=0){
            rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
            adapter = new MultiImageAdapter(this, mAddPicClickListener);
            adapter.setList(selectList);
            rvImageRV.setAdapter(adapter);
            adapter.setOnItemClickListener(new MultiImageAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(final int position, View v) {
                    String type = selectList.get(position).getSuffixType();
                    String path = selectList.get(position).getPath();
                    if(".mp4".equalsIgnoreCase(type)){
                        startActivity(new Intent(AddServiceRecordActivity.this, VideoPlayerActivity.class).putExtra(
                                "path",path));
                    }else if(".wav".equalsIgnoreCase(type) || ".amr".equalsIgnoreCase(type)){
                        if (audioDialog!=null){
                            audioDialog.startPlay(path);
                        }
                    }else {
                        startActivity(new Intent(AddServiceRecordActivity.this, ImagePlayActivity.class).putExtra(
                                "path", path));
                    }
                }
            });
        }else {
            rvImageRV.setVisibility(View.GONE);
        }
        tv_Time.setText(BaseUtil.TimeForData(System.currentTimeMillis()));

        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if ("AddServiceRecordActivity".equals(bean.getRequest())) {
                            if (bean.getType()==0){//服务人员
                                servicerBean= (ServicerBean.RowsBean) bean.getMsg();
                                tv_Worker.setText(servicerBean.getMemberName());
                            }
                            if (bean.getType()==1){//服务对象
                                serviceObjBean= (ServiceObjectBean.RowsBean) bean.getMsg();
                                tv_WorkerObject.setText(serviceObjBean.getObjectName());
                            }
                            if (bean.getType()==3){//服务对象的大类
                                objectMoudle = (String) bean.getMsg();
                            }
                            if (bean.getType()==4){//服务对象小类
                                objectType = (String) bean.getMsg();
                            }
                        }
                    }
                });

    }

    @OnClick({R.id.tv_right,R.id.tv_Worker,R.id.tv_WorkerObject})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_right:
                submit();
                break;
            case R.id.tv_Worker://服务人员选择
                startActivity(new Intent(this,ServicerSelectActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"AddServiceRecordActivity"));
                break;
            case R.id.tv_WorkerObject://服务对象
                startActivity(new Intent(this,ServiceObjectActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"AddServiceRecordActivity"));
                break;

        }
    }

    private void submit() {
        String time = tv_Time.getText().toString().trim();
        if (BaseUtil.isEmpty(time)){
            ToastUtils.showToast(this,"请选择服务时间");
            return;
        }
        if (servicerBean==null){
            ToastUtils.showToast(this,"请选择服务人员");
            return;
        }
        if (serviceObjBean==null){
            ToastUtils.showToast(this,"请选择服务对象");
            return;
        }
        String content=et_ServiceContent.getText().toString().trim();
        if (BaseUtil.isEmpty(content)){
            et_ServiceContent.setError("服务内容不能为空");
            return;
        }
        if (FILE_TYPE == 0){
            LoadDialog.show(AddServiceRecordActivity.this, "正在提交...");
            submitDone();
        }else {
            if (selectList.size() == 0){
                ToastUtils.showToast(this,"请添加附件");
                return;
            }
            List<File> files = new ArrayList<>();
            for (PhotoBean localMedia : selectList) {
                files.add(new File(localMedia.getPath()));
            }
            LoadDialog.show(AddServiceRecordActivity.this, "正在提交...");
            new UploadFilePest(AddServiceRecordActivity.this).uploadFile(this, files);
        }
    }

    private void submitDone() {
        String time=tv_Time.getText().toString();
        String local=et_ServiceLocal.getText().toString().trim();
        String other=et_OtherWorker.getText().toString().trim();
        String content=et_ServiceContent.getText().toString().trim();
        ServiceRecordDetailPest recordDetailPest =new ServiceRecordDetailPest(this);
        recordDetailPest.addServiceRecord(type.get(FILE_TYPE),time,local,other,content,
                servicerBean,serviceObjBean,objectMoudle,objectType,upDatafile);
    }

    @Override
    protected void onDestroy() {
        if (disposable!=null&&disposable.isDisposed()){
            disposable.dispose();
        }
        super.onDestroy();
    }


    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                switch (FILE_TYPE){
                    case 1://图片
                        PictureSelector.create(AddServiceRecordActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.MULTIPLE)
                                .maxSelectNum(max)// 最大图片选择数量 int
//                                .enableCrop(true)
//                                .withAspectRatio(4,3)
                                .compress(true)
                                .compressGrade(Luban.CUSTOM_GEAR)
                                .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case 2://音频
                        if (audioDialog==null){
                            audioDialog=new AudioDialog(AddServiceRecordActivity.this);
                            audioDialog.setCancelable(false);
                            audioDialog.getAudioBack(new AudioDialog.AudioCallback() {
                                @Override
                                public void getData(String filePath, int countdown) {
                                    PhotoBean photoBean = new PhotoBean(filePath, ".amr");
                                    selectList.add(photoBean);
                                    if (adapter != null) adapter.notifyDataSetChanged();
                                }
                            });
                        }
                        audioDialog.show(audioDialog.AUDIO_RECODERD);
                        break;
                    case 3://视频
                        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                                .smallVideoWidth(640)
                                .smallVideoHeight(480)
                                .recordTimeMax(10 * 1000)
                                .maxFrameRate(20)
                                .minFrameRate(8)
                                .captureThumbnailsTime(1)
                                .videoBitrate(580000)
                                .build();
                        MediaRecorderActivity.goSmallVideoRecorder(AddServiceRecordActivity.this,
                                DisputeAddActivity.class.getName(), config);
                        break;
                }
            } else {
                ToastUtils.showToast(AddServiceRecordActivity.this,"最多上传三项");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case MediaRecorderActivity.FOR_RESULT://拍视频
                    String videoUri = data.getStringExtra(MediaRecorderActivity.VIDEO_URI);
                    if (!TextUtils.isEmpty(videoUri)) {
                        String type = videoUri.substring(videoUri.lastIndexOf("."));
                        selectList.add(new PhotoBean(videoUri, type));
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    /**
     * 文件上传成功
     * @param beans
     */
    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        if (beans !=null && beans.size()>0){
            upDatafile=beans;
            submitDone();
        }else {
            LoadDialog.dismiss(this);
            ToastUtils.showToast(this,"服务器异常上传文件失败");
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }

    /**
     * 提交成功
     * @param detailBean
     */
    @Override
    public void getServiceRecordDetail(ServiceRecordDetailBean detailBean) {
        LoadDialog.dismiss(this);
        if (detailBean!=null){
            MyRxBus.get().post(new MsgEvent<>(currentActivity,2,"提交成功"));
            finish();
        }
    }
}
